﻿// Copyright (c) 2014 Bryan C. O'Connell
// http://wsubi.codeplex.com/license
// Purpose: Defines the 'info' command. This command returns the |info| 
// documentation text contained within the specified script file.

using System;
using System.Collections.Generic;
using Wsubi.Code.Utilities;

namespace Wsubi.Code.Commands
{
    public class Info : ICommand
    {
        public string Target { get; set; }
        public string Params { get; set; }
        public ScriptData ScriptDataStorage { get; set; }

        private ResultSet _Results;

        private const string INFO_TAG = "|info|";

        public string GetActionKeyword() {
            return "info";
        }

        public ResultSet Execute()
        {
            Guard.CheckForNullObject(ScriptDataStorage);

            string ScriptContents = GetScriptContents(Target.ToLower());
            string InfoText = ExtractInfoText(ScriptContents);

            BuildResultSet(InfoText);
            return _Results;
        }

        private string GetScriptContents(string NameOfScript) 
        {
            Dictionary<string, string> ScriptBin = ScriptDataStorage.ShareScriptFileBin();            
            Guard.CheckForKey(ScriptBin, NameOfScript);

            string ScriptContents = ScriptBin[NameOfScript].ToLower();
            Guard.CheckForEmptyString(ScriptContents);

            return ScriptContents;
        }

        private string ExtractInfoText(string ScriptContents)
        {
            string InfoText = String.Empty;

            int OpenTagPosition = ScriptContents.IndexOf(INFO_TAG);
            int CloseTagPosition = ScriptContents.LastIndexOf(INFO_TAG);
            bool InfoTextFound = InfoSectionIsWellFormatted(OpenTagPosition, CloseTagPosition);

            if (InfoTextFound) {
                InfoText = ScriptContents.Remove(CloseTagPosition, (ScriptContents.Length - CloseTagPosition));
                InfoText = InfoText.Remove(0, OpenTagPosition + INFO_TAG.Length);    
            } 
            else {
                InfoText = "Unable to retrieve INFO. No " + INFO_TAG + " found in " + Target + " or section may be improperly formatted."; ;
            }

            return InfoText;
        }

        private bool InfoSectionIsWellFormatted(int OpenTagPosition, int CloseTagPosition)
        {
            if ((OpenTagPosition > -1) && (CloseTagPosition > -1) && (OpenTagPosition != CloseTagPosition)) {
                return true;
            } else {
                return false;
            }
        }

        private void BuildResultSet(string InfoText) 
        {
            _Results = new ResultSet();
            _Results.AddResult(InfoText);
            _Results.OutputTo = OutputsTo.Screen;
        }
    }
}
